

"""
cache.lookup({'realm': realm, 'file': file})
cache.update({'realm': realm, 'file': file'}, {'cache': cache})
cache.delete({'realm': realm, 'file': file'})

"""

import json, os.path, sqlite3

class MemoryCacheRealm:
	"""A realm is a file->props mapping"""
	def __init__(self, dataSet):
		self._data=dataSet

	def record(self, fileName, props):
		record=self.lookup(fileName)
		record.update(props)
		self._data[fileName]={key: value for key, value in record.iteritems() if value}
	
	def lookup(self, fileName):
		return self._data.get(fileName, {})
	
	def delete(self, fileName):
		if self._data.has_key(fileName):
			del self._data[fileName]
			
	def find(self, status='all'):
		if status=='all':
			return self._data.keys()
		else:
			return [f for f in self._data.keys() if self._data[f].get('pending')==status]


class MemoryCache:
	"""Cache consist of several realms"""
	def __init__(self, data={}):
		self._data=data
		
	def getRealm(self, name):
		if not self._data.has_key(name):
			self._data[name]={}
		return MemoryCacheRealm(self._data[name])
	
	def serialize(self):
		return json.dumps(self._data, indent=4)
	
	def unserialize(self, data):
		self._data=json.loads(data)




class SQLiteCache:
	
	def __init__(self, connection):
		self._sqlite=sqlite3.connect(os.path.expanduser('~/.sachem/file-cache.sqlite'))
		with self._connection.cursor() as c:
			 c.execute("CREATE TABLE IF NOT EXISTS files ("+
			           "url TEXT PRIMARY KEY, " +
			           "stamp TEXT, " +
			           "hash TEXT, " +
			           "pending TEXT)")

	def lookup(self, url):
		return self._getProp(url, 'stamp')
		try:
			with self._connection.cursor() as c:
				c.execute("SELECT * FROM files WHERE url=:url", {'url':url})
				row=self._con.fetchone()
				result = {}
				for idx, col in enumerate(c.description):
					result[col[0]] = row[idx]
				return result
		except:
			print 'sqlite error occured'
			return {}
			
	def update(self, url, props):
		allowed=set(['stamp', 'hash', 'pending'])
		try:
			with self._connection.cursor() as c:
				for prop in set(props.keys()).intersection(allowed):
					c.execute(
						"INSERT OR REPLACE INTO files (url, %s) "+
						"VALUES (:url, :value)"%prop, 
						{'url':url, 'value':props[prop]}
					)
		except:
			print 'sqlite error occured'
				


defaultInstance=None
#defaultInstance.unserialize(data)

